<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
      <!--基本信息-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>基本信息</span></div>

        <el-form :inline="false" :rules="baseFormRules" :model="baseForm" :size="size" ref="baseForm">
          <el-row>
            <el-form-item label="录入方式">
              <span>人工下单</span>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="销售商家：" prop="merchantId">
                <el-select v-model="baseForm.merchantId"  value-key="id" @change="changMerchant" placeholder="请选择">
                  <el-option v-for="item in merchantOptions" :key="item.id" :label="item.name" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售渠道：" prop="channelId">
                <el-select v-model="baseForm.channelId" @change="changChannel" placeholder="请选择">
                  <el-option v-for="item in channelOptions" :key="item.channelId" :label="item.channelName" :value="item.channelId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售店铺：" prop="storeId">
                <el-select v-model="baseForm.storeId" value-key="id" @change="changeStore" placeholder="请选择">
                  <el-option v-for="item in storeOptions" :key="item.id" :label="item.storeName" :value="item" :value-key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!--下单账户信息-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>下单账户信息</span></div>

        <el-form :inline="true" :model="memberForm" :rules="memberFormRules" :size="size" ref="memberForm">
          <el-form-item label="ID：" prop="memberId" v-if="false">
            <el-input v-model="memberForm.memberId" :disabled="true" label-width="80px" auto-complete="off"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="会员号：" prop="nickname">
                <el-input v-model="memberForm.nickname" :readonly="true" style="width: 220px" @focus="selectMember" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="会员姓名：" prop="username">
                <el-input v-model="memberForm.username" :disabled="true" style="width: 220px" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="会员手机：" prop="mobile">
                <el-input v-model="memberForm.mobile" :disabled="true" style="width: 220px" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="会员邮箱：" prop="email">
                <el-input v-model="memberForm.email" :disabled="true" style="width: 220px" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!--收货信息-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>收货信息</span></div>

        <el-form :inline="false" :model="receiptForm" label-width="110px" :rules="receiptFormRules" :size="size" ref="receiptForm">
          <el-row>
            <el-col :span="8">
              <el-form-item label="收货人姓名：" prop="receiverName">
                <el-input v-model="receiptForm.receiverName" style="width: 300px" placeholder="请输入收货人姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货人手机：" prop="receiverPhone">
                <el-input v-model="receiptForm.receiverPhone" style="width: 300px" placeholder="请输入收货人手机"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货地址：" prop="receiverArea">
                <v-distpicker v-model="receiptForm.receiverArea"
                              :province="receiptForm.receiverProvinceName"
                              :city="changeProvince.receiverCityName"
                              :area="receiptForm.receiverRegionName"
                              @selected="changeProvince"></v-distpicker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="详细地址：" prop="receiverAddress">
                <el-input v-model="receiptForm.receiverAddress" style="width: 300px" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户备注：" prop="userMark">
                <el-input type="textarea" style="width: 300px" v-model="receiptForm.userMark" placeholder="请输入客户备注"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商家备注：" prop="merchantMark">
                <el-input type="textarea" style="width: 300px" v-model="receiptForm.merchantMark" placeholder="请输入商家备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="平台备注：" prop="deptMark">
              <el-input type="textarea" style="width: 300px" v-model="receiptForm.deptMark" placeholder="请输入平台备注"></el-input>
            </el-form-item>
            <el-form-item label="附件：">
              <div style="width: 300px">
                <el-upload class="upload-demo" :action="imgUpload" multiple :on-success="hanleSuccesss" :on-remove="handleRemove" :limit="3" :file-list="fileList">
                  <el-button size="small" round type="primary">添加附件</el-button>
                </el-upload>
              </div>
            </el-form-item>
          </el-row>
        </el-form>
      </el-card>

      <!--发运计划-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>发运计划</span></div>

        <el-form :inline="false" :model="shippingPlanForm" label-width="120px" :rules="shippingPlanFormRules" :size="size" ref="shippingPlanForm">
          <el-row>
            <el-col :span="8">
              <el-form-item label="预计发货日期：" prop="deliveryTime">
                <el-date-picker v-model="shippingPlanForm.deliveryTime" type="date" placeholder="请选择预计发货日期"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="配送方式：" prop="deliveryType">
                <el-select v-model="shippingPlanForm.deliveryType" placeholder="请选择配送方式">
                  <el-option :value="1" label="快递物流">快递物流</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!--支付和结算-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>发运计划</span></div>

        <el-form :inline="false" :model="payForm" label-width="120px" :rules="payFormRules" :size="size" ref="payForm">
          <el-row>
            <el-col :span="8">
              <el-form-item label="币别码：" prop="currency">
                <el-select v-model="payForm.currency" placeholder="请选择币别码">
                  <el-option v-for="item in currencyOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="付款类型：" prop="payType">
                <el-select v-model="payForm.payType" placeholder="请选择付款类型">
                  <el-option v-for="item in payTypeoptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!--商品信息-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>商品信息</span></div>

        <el-row style="margin-bottom: 20px; text-align: right">
          <el-button size="small" type="primary" @click="batchDeleteProduct" round>批量删除</el-button>
          <el-button size="small" @click="addProduct" round>添加商品</el-button>
        </el-row>

        <el-table :data="tableProductData"
                  @selection-change="handleProductSelectedChange"
                  style="width: 100%"
                  :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="date" label="商品主图">
            <template slot-scope="scope"><img :src="scope.row.pictureUrl" style="width: 60px;height: 60px"/></template>
          </el-table-column>
          <el-table-column prop="chineseName" label="商品名称" width="500px"></el-table-column>
          <el-table-column prop="code" label="商品编码" width="200"></el-table-column>
          <el-table-column prop="propertyName" label="规格属性" width="200"></el-table-column>
          <el-table-column prop="artNo" label="货号" width="200"></el-table-column>
          <el-table-column prop="barCode" label="条码" width="200"></el-table-column>
          <el-table-column prop="date" label="品牌类目" width="400">
            <template slot-scope="scope">
              <span>{{scope.row.brandName}}&nbsp&nbsp{{scope.row.fullNamePath}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="可售库存" width="200"></el-table-column>
          <el-table-column prop="minNum" label="最小起订量" width="200"></el-table-column>
          <el-table-column prop="orderMultiple" label="订货倍数" width="200"></el-table-column>
          <el-table-column prop="goodsNum" label="订购数量" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsNum" @change="changeProduct(scope.row,scope.$index)" placeholder="请输入订购数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="定价方式">
            <template slot-scope="scope">
              <span>固定价</span>
            </template>
          </el-table-column>
          <el-table-column prop="salePriceWithTax1" width="150" label="销售单价"></el-table-column>
          <el-table-column prop="salePriceWithTax" width="150" label="购买单价	">
            <template slot-scope="scope">
              <el-input v-model="scope.row.salePriceWithTax" @change="changeProduct(scope.row,scope.$index)" placeholder="请输入购买单价"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="buyTotalAmount" label="购买金额	" width="150"></el-table-column>
          <el-table-column prop="currency" label="币别码"></el-table-column>
          <el-table-column prop="contractNo" label="合同编号"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDeleteProduct(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!--订单合计-->
      <el-card class="box-card" style="margin-bottom: 20px;text-align: left;width:100%;height: auto;">
        <div slot="header" class="clearfix"><span>订单合计</span></div>

        <el-form :inline="false" :model="orderForm" label-width="120px" :size="size" ref="orderForm">
          <el-row>
            <el-form-item label="商品数量合计：" prop="totalGoodsNum">
              <span>{{orderForm.totalGoodsNum}}</span>
            </el-form-item>
            <el-form-item label="商品金额合计：" prop="totalGoodsNum">
              <span>{{orderForm.buyTotalAmount}}</span>
            </el-form-item>
            <el-form-item label="运费：" prop="expressTotalFee">
              <el-input v-model="orderForm.expressTotalFee" @change="changeExpressTotalFee" style="width: 200px" placeholder="请输入运费"></el-input>
            </el-form-item>
            <el-form-item label="订单金额合计：" prop="actualPayTotalAmount">
              <span>{{orderForm.actualPayTotalAmount}}</span>
            </el-form-item>
          </el-row>
        </el-form>
      </el-card>

      <!--提交-->
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-bottom: 40px">
        <el-button :size="size" @click="goIndex">{{$t("action.cancel")}}</el-button>
        <el-button :size="size" type="primary"  :loading="editLoading" @click.native="submitOrderForm">提交订单</el-button>
      </div>
    </div>

    <!--会员列表弹框-->
    <el-dialog title="请选择会员" width="60%" :visible.sync="memberDialogVisible" :close-on-click-modal="false">
      <el-form :inline="true" :model="memberFilters" :size="size">
        <el-form-item label="会员号：">
          <el-input v-model="memberFilters.nickname" placeholder="会员号"></el-input>
        </el-form-item>
        <el-form-item label="会员姓名：">
          <el-input v-model="memberFilters.username" placeholder="会员姓名"></el-input>
        </el-form-item>
        <el-form-item label="会员手机：">
          <el-input v-model="memberFilters.mobile" placeholder="会员手机"></el-input>
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-search" :label="$t('action.search')" type="primary" @click="findMemberPage"/>
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetMemberFiltersForm('memberFilters')"/>
        </el-form-item>
      </el-form>

      <el-table :data="tableMemberData"
                ref="multipleTable"
                @selection-change="handleSelectionChange"
                :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
                style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="nickname" :show-overflow-tooltip="true" label="会员号"></el-table-column>
        <el-table-column prop="username" label="会员姓名"></el-table-column>
        <el-table-column prop="mobile" label="会员手机"></el-table-column>
      </el-table>

      <div class="toolbar" style="padding:10px;">
        <el-pagination layout="total, prev, pager, next, jumper,sizes"
                       @current-change="refreshPageRequest"
                       @size-change="handleSizeChange"
                       :current-page="pageRequest.pageNum"
                       :page-size="pageRequest.pageSize"
                       :total="totalSize"
                       style="float:right;"
                       :page-sizes="[10, 20, 30, 40]"></el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button :size="size" @click.native="memberDialogVisible = false">{{ $t("action.cancel") }}</el-button>
        <el-button :size="size" type="primary" @click="submitMember">{{ $t("action.submit") }}</el-button>
      </div>
    </el-dialog>

    <!--商品列表弹框-->
    <el-dialog title="请选择商品" width="60%" :visible.sync="productDialogVisible" :close-on-click-modal="false">
      <el-form :inline="true" :model="productFilters" :size="size">
        <el-form-item>
          <el-input v-model="productFilters.chineseName" placeholder="商品名称"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="productFilters.code" placeholder="商品编码"/>
        </el-form-item>
        <el-form-item>
          <tree-select :options="categoryOptions"
                       placeholder="商品类目"
                       v-model="productFilters.productCategoryId"
                       :normalizer="normalizer"
                       style="width:230px"/>
        </el-form-item>
        <el-form-item>
          <el-select v-model="productFilters.brandId" style="width: 200px" placeholder="商品品牌">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-search" :label="$t('action.search')" type="primary" @click="findProductPage"/>
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetProductFiltersForm('productFilters')"/>
        </el-form-item>
      </el-form>

      <el-table :data="pageResult1"
                :size="size"
                align="align"
                style="width: 100%"
                @selection-change="handleProductSelectionChange"
                :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="chineseName" label="商品名称" width="400px"></el-table-column>
        <el-table-column prop="code" label="商品编码" width="200px"></el-table-column>
        <el-table-column prop="stock" label="可售库存"></el-table-column>
        <el-table-column prop="minNum" label="最小起订量"></el-table-column>
        <el-table-column prop="orderMultiple" label="订货倍数"></el-table-column>
        <el-table-column prop="propertyName" label="规格属性"></el-table-column>
        <el-table-column prop="artNo" label="货号" width="200px"></el-table-column>
        <el-table-column prop="barCode" label="条码" width="200px"></el-table-column>
        <el-table-column prop="brandName" label="品牌" width="200px"></el-table-column>
        <el-table-column prop="fullNamePath" label="类目" width="300"></el-table-column>
        <el-table-column prop="unitsName" label="计量单位"></el-table-column>
        <el-table-column prop="currency" label="币别码"></el-table-column>
        <el-table-column prop="contractNo" label="合同编号"></el-table-column>
      </el-table>

      <!--分页栏-->
      <div class="toolbar" style="padding:10px;">
        <el-pagination layout="total, prev, pager, next, jumper,sizes"
                       @current-change="refreshPageRequest"
                       @size-change="handleSizeChange"
                       :current-page="pageRequest1.pageNum"
                       :page-size="pageRequest1.pageSize"
                       :total="totalSize1"
                       style="float:right;"
                       :page-sizes="[10, 20, 30, 40]"></el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button :size="size" @click.native="productDialogVisible = false">{{ $t("action.cancel") }}</el-button>
        <el-button :size="size" type="primary" @click="submitFormProduct">{{ $t("action.submit") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
	import VDistpicker from 'v-distpicker'
	import KtButton from '@/views/Core/KtButton'
	import TableColumnFilterDialog from '@/views/Core/TableColumnFilterDialog'
	import CyTable from '@/views/Core/ProductTable'
	import FreightTemplate from '../Configuration/FreightTemplate'
	import TreeSelect from '@riophae/vue-treeselect'
	import '@riophae/vue-treeselect/dist/vue-treeselect.css'

	export default {
		components: {
			FreightTemplate,
			KtButton,
			CyTable,
			TableColumnFilterDialog,
			VDistpicker,
			TreeSelect
		},

		data() {
			return {
				editLoading: false,
				fileList: [],
				imgUpload: 'http://139.217.220.198:8094/api/upload',
				//已经选中的商品
				productSelected: [],
				//商品选择
				productSelect: [],
				//商品类目集合
				categoryOptions: [],
				//商品品牌集合
				brandList: [],
				//商品弹框
				productDialogVisible: false,
				//商品列表条件查询
				productFilters: {
					chineseName: '',
					productCategoryId: null,
					brandId: '',
					code: '',
					flag: 2
				},
				//商品数据
				tableProductData: [],
				currencyOptions: [{value: '1', label: '人民币'}, {value: '2', label: '美元'}],
				payTypeoptions: [{value: '1', label: '网上支付'}, {value: '2', label: '线下支付'}],
				//选中的会员数据
				memberSelect: [],
				//会员删选条件
				memberFilters: {
					userAccount: '',
					nicknameame: '',
					mobile: ''
				},
				storeLogoUrl: '',//选中的店铺Logo
				storeName: '',//选中的店铺名称
				storeId: '',//选中的店铺id
				merchantName: '',//选中的商家名称
				merchantId: '',//选中的商家id
				storeOptions: [],//店铺集合
				channelOptions: [],//渠道集合
				merchantOptions: [],//商家集合
				size: 'small',
				//基本信息
				baseForm: {
					merchantId: '',
					channelId: '',
					storeId: ''
				},
				baseFormRules: {
					merchantId: [{required: true, message: '请选择商家', trigger: 'change'}],
					channelId: [{required: true, message: '请选择店铺', trigger: 'change'}],
					storeId: [{required: true, message: '请选择店铺', trigger: 'change'}]
				},
				//下单账户信息
				memberForm: {
					nickname: '',
					username: '',
					mobile: '',
					email: '',
					memberId: ''
				},
				memberFormRules: {
					nickname: [{required: true, message: '请选择会员号', trigger: 'change'}]
				},
				//收货信息
				receiptForm: {
					receiverName: '',
					receiverPhone: '',
					receiverAddress: '',
					userMark: '',
					merchantMark: '',
					deptMark: '',
					receiverArea: '',
					receiverProvinceId: '',
					receiverProvinceName: '',
					receiverCityId: '',
					receiverCityName: '',
					receiverCountryId: '',
					receiverRegionName: ''
				},
				receiptFormRules: {
					receiverName: [{required: true, message: '请输入收货人姓名', trigger: 'blur'}],
					receiverPhone: [{required: true, message: '请输入收货人手机', trigger: 'blur'}],
					// receiverArea: [{required: true, message: "请选择收货地址", trigger: "change"}],
					receiverAddress: [{required: true, message: '请输入详细地址', trigger: 'blur'}]
				},
				//发运计划
				shippingPlanForm: {
					deliveryTime: '',
					deliveryType: ''
				},
				shippingPlanFormRules: {
					deliveryTime: [{required: true, message: '请选择预计发货日期', trigger: 'change'}],
					deliveryType: [{required: true, message: '请选择配送方式', trigger: 'change'}]
				},
				//支付和结算
				payForm: {
					currency: '',
					payType: ''
				},
				payFormRules: {
					currency: [{required: true, message: '请选择币别', trigger: 'change'}],
					payType: [{required: true, message: '请选择结算方式', trigger: 'change'}]
				},
				//订单合计
				orderForm: {
					totalGoodsNum: 0,
					buyTotalAmount: 0,
					expressTotalFee: 0,
					actualPayTotalAmount: 0
				},
				tableMemberData: [],//会员数据
				pageRequest: {pageNum: 1, pageSize: 10},
				pageRequest1: {pageNum: 1, pageSize: 10},
				pageResult: [],
				pageResult1: [],
				totalSize: 0,
				totalSize1: 0,
				memberDialogVisible: false //会员弹框
			}
		},

		methods: {
			//返回
			goIndex: function() {
				this.$router.go(-1)
			},
			//附件移除回调
			handleRemove: function(file, fileList) {
				this.fileList = fileList
			},
			//附件上传成功回调
			hanleSuccesss: function(res, file, fileList) {
				let obj = {}
				obj.imgUrl = res.data.imgUrl
				obj.name = file.name
				this.fileList.push(obj)
			},
			//修改运费
			changeExpressTotalFee: function() {
				this.orderForm.actualPayTotalAmount = Number(this.orderForm.buyTotalAmount) + Number(this.orderForm.expressTotalFee)
			},
			//提交订单
			submitOrderForm: function() {
				let this_ = this
				if (this.tableProductData.length == 0) {
					this_.$message({message: '请先添加商品, ', type: 'info'})
				} else {
					let param = {}
					param.orderType = 1
					param.serialNo = 'O' + new Date().getTime()
					param.saleChannel = this_.baseForm.channelId
					param.buyerId = this_.memberForm.memberId
					param.buyerUsername = this_.memberForm.nickname
					param.receiverName = this_.receiptForm.receiverName
					param.receiverPhone = this_.receiptForm.receiverPhone
					param.receiverAddress = this_.receiptForm.receiverAddress
					param.saleTotalAmount = this_.orderForm.buyTotalAmount
					param.buyTotalAmount = this_.orderForm.buyTotalAmount
					param.expressTotalFee = this_.orderForm.expressTotalFee
					param.actualPayTotalAmount = this_.orderForm.actualPayTotalAmount
					param.receiverProvinceId = this_.receiptForm.receiverProvinceId
					param.receiverProvinceName = this_.receiptForm.receiverProvinceName
          param.receiverCityId=this_.receiptForm.receiverCityId
          param.receiverCityName=this_.receiptForm.receiverCityName
          param.receiverCountryId=this_.receiptForm.receiverCountryId
          param.receiverRegionName=this_.receiptForm.receiverRegionName
          let createOrderRequestList = new Array()
          let obj = {}
          obj.merchantId = this_.merchantId
          obj.merchantName = this_.merchantName
          obj.storeId = this_.storeId
          obj.storeName = this_.storeName
          obj.storeLogoUrl = this_.storeLogoUrl
          obj.saleTotalAmount = this_.orderForm.buyTotalAmount
          obj.saleTotalAmount = this_.orderForm.buyTotalAmount
          obj.expressTotalFee = this_.orderForm.expressTotalFee
          obj.actualPayTotalAmount = this_.orderForm.actualPayTotalAmount
          let goodsList = new Array();
          this_.tableProductData.forEach(item => {
            let goods = {}
            goods.goodsId = item.id
            goods.goodsType = 1
            goods.goodsNum = item.goodsNum
            goods.goodsName = item.chineseName
            goods.goodsImgUrl = item.pictureUrl
            goods.merchantId = this_.merchantId
            goods.merchantName = this_.merchantName
            goods.storeId = this_.storeId
            goods.storeName = this_.storeId
            goods.storeLogoUrl = this_.storeLogoUrl
            goods.saleUnitPrice = item.salePriceWithTax
            goods.buyUnitPrice = item.salePriceWithTax
            goods.actualPayTotalAmount = Number(item.goodsNum) * Number(item.salePriceWithTax)
            goodsList.push(goods)
          })
          obj.goodsList = goodsList
          createOrderRequestList.push(obj)
          param.createOrderRequestList = createOrderRequestList
          this_.editLoading = true;
          this.utils.request.saveManualOrder(param, function (res) {
            if (res.code == "0000") {
              this_.$message({message: "操作成功, ", type: "success"});
              this_.$router.go(-1);
              this_.editLoading = false;
            } else {
              this_.$message({message: "操作失败, " + data.msg, type: "error"});
              this_.editLoading = false;
            }
          })
        }

      },
      //商品价格和数量修改
      changeProduct: function (row, index) {
        let this_ = this
        this_.tableProductData[index].buyTotalAmount = Number(row.goodsNum) * Number(row.salePriceWithTax);
        let obj = this_.tableProductData[index]
        this_.tableProductData.splice(index, 1)
        this_.tableProductData.push(obj)
        //计算订单信息
        let totalGoodsNum = Number(0)
        let buyTotalAmount = Number(0)
        let actualPayTotalAmount = Number(0)
        this_.tableProductData.forEach(item => {
          totalGoodsNum += Number(item.goodsNum)
          buyTotalAmount += Number(item.buyTotalAmount)
        })
        this_.orderForm.totalGoodsNum = totalGoodsNum
        this_.orderForm.buyTotalAmount = buyTotalAmount
        this_.orderForm.actualPayTotalAmount = buyTotalAmount + Number(this_.orderForm.expressTotalFee)

      },
      //勾选已添加商品
      handleProductSelectedChange: function (param) {
        this.productSelected = []
        this.productSelected = param
      },
      //批量删除
      batchDeleteProduct: function () {
        let this_ = this
        if (this_.productSelected.length == 0) {
          this_.$message({message: "请选择要操作的商品, ", type: "info"});
        } else {
          this_.tableProductData = this_.getArray(this_.tableProductData, this_.productSelected)
          //计算订单信息
          let totalGoodsNum = Number(0)
          let buyTotalAmount = Number(0)
          this_.tableProductData.forEach(item => {
            totalGoodsNum += Number(item.goodsNum)
            buyTotalAmount += Number(item.buyTotalAmount)
          })
          this_.orderForm.totalGoodsNum = totalGoodsNum
          this_.orderForm.buyTotalAmount = buyTotalAmount
          this_.orderForm.actualPayTotalAmount = buyTotalAmount + Number(this_.orderForm.expressTotalFee)
        }

      },
      getArray: function (arr1, arr2) {
        var set2 = new Set(arr2);
        var subset = [];
        arr1.forEach(function (val, index) {
          if (!set2.has(val)) {
            subset.push(val);
          }
        });
        return subset;
      },
      //删除商品
      handleDeleteProduct: function (row, index) {
        let this_ = this
        this.tableProductData.splice(index, 1)
        //计算订单信息
        let totalGoodsNum = Number(0)
        let buyTotalAmount = Number(0)
        let actualPayTotalAmount = Number(0)
        this_.tableProductData.forEach(item => {
          totalGoodsNum += Number(item.goodsNum)
          buyTotalAmount += Number(item.buyTotalAmount)
        })
        this_.orderForm.totalGoodsNum = totalGoodsNum
        this_.orderForm.buyTotalAmount = buyTotalAmount
        this_.orderForm.actualPayTotalAmount = buyTotalAmount + Number(this_.orderForm.expressTotalFee)
      },
      //提交商品
      submitFormProduct: function () {
        let this_ = this
        if (this_.productSelect.length == 0) {
          this_.$message({message: "请选择要添加的商品, ", type: "info"});
        } else {
          if (this_.tableProductData.length == 0) {
            this_.productSelect.forEach(item => {
              this_.$set(item, 'goodsNum', 1)
              item.buyTotalAmount = item.salePriceWithTax
            })
            this_.tableProductData = this_.productSelect
            //计算订单信息
            let totalGoodsNum = Number(0)
            let buyTotalAmount = Number(0)
            let actualPayTotalAmount = Number(0)
            this_.tableProductData.forEach(item => {
              totalGoodsNum += Number(item.goodsNum)
              buyTotalAmount += Number(item.buyTotalAmount)
            })
            this_.orderForm.totalGoodsNum = totalGoodsNum
            this_.orderForm.buyTotalAmount = buyTotalAmount
            this_.orderForm.actualPayTotalAmount = buyTotalAmount + Number(this_.orderForm.expressTotalFee)
          } else {
            this_.productSelect.forEach(item => {
              this_.$set(item, 'goodsNum', 1)
              item.buyTotalAmount = item.salePriceWithTax
            })
            this_.tableProductData.forEach(item1 => {
              this_.productSelect.forEach(function (item, index) {
                if (item.id == item1.id) {
                  this_.productSelect.splice(index, 1)
                }
              })
            })
            this_.tableProductData = this_.tableProductData.concat(this_.productSelect)
            //计算订单信息
            let totalGoodsNum = Number(0)
            let buyTotalAmount = Number(0)
            let actualPayTotalAmount = Number(0)
            this_.tableProductData.forEach(item => {
              totalGoodsNum += Number(item.goodsNum)
              buyTotalAmount += Number(item.buyTotalAmount)
            })
            this_.orderForm.totalGoodsNum = totalGoodsNum
            this_.orderForm.buyTotalAmount = buyTotalAmount
            this_.orderForm.actualPayTotalAmount = buyTotalAmount + Number(this_.orderForm.expressTotalFee)
          }
          this_.productDialogVisible = false
        }
      },
      //勾选商品
      handleProductSelectionChange: function (param) {
        this.productSelect = param
      },
      // 获取商品数据
      findProductPage: function (params) {
        let this_ = this
        if (params == undefined || params == null) {
          params = {
            pageNum: this_.pageRequest1.pageNum,
            pageSize: this_.pageRequest1.pageSize
          };
        }
        if (this_.productFilters == undefined || this_.productFilters == null) {
          this_.productFilters = {};
        }
        this_.productFilters.start = params.pageNum;
        this_.productFilters.limit = params.pageSize;
        this_.productFilters.merchantId = this.merchantId
        this_.productFilters.storeId = this.storeId
        this.utils.request.queryShopProductPage(this_.productFilters, function (res) {
          this_.pageResult1 = res.data.rows;
          this_.totalSize1 = Number(res.data.total);
        });
      },
      //查询所有品牌
      queryProductBrand() {
        let _this = this;
        this.utils.request.queryProductBrand({}, function (data) {
          if (data.data != null) {
            _this.brandList = data.data;
          }
        });
      },
      //格式化商品类目查询条件
      normalizer(node) {
        if (node.categoryList == null || node.categoryList.length == 0) {
          delete node.categoryList;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.categoryList
        }
      },
      //查询后台类目
      queryBehindCategory: function () {
        let params = {};
        let this_ = this
        this.utils.request.queryBehindCategory(params, function (data) {
          if (data.data != null) {
            this_.categoryOptions = data.data
          }
        });
      },
      //添加商品
      addProduct: function () {
        this.productSelect = []
        let flag = true
        this.$refs['baseForm'].validate((valid) => {
          if (!valid) {
            this.$message({message: "请完善基本信息, ", type: "info"});
            flag = false;
            return flag
          }
        });
        if (flag) {
          this.$refs['memberForm'].validate((valid) => {
            if (!valid) {
              this.$message({message: "请完善会员信息, ", type: "info"});
              flag = false;
              return flag
            }
          });
        }
        if (flag) {
          this.$refs['receiptForm'].validate((valid) => {
            if (!valid) {
              this.$message({message: "请完善收货信息, ", type: "info"});
              flag = false;
              return flag
            }
          });
        }
        if (flag) {
          this.$refs['shippingPlanForm'].validate((valid) => {
            if (!valid) {
              this.$message({message: "请完善发运信息, ", type: "info"});
              flag = false;
              return flag
            }
          });
        }
        if (flag) {
          this.$refs['payForm'].validate((valid) => {
            if (!valid) {
              this.$message({message: "请完善支付信息, ", type: "info"});
              flag = false;
              return flag
            }
          });
        }
        if (flag) {
          this.productDialogVisible = true
          this.findProductPage()
        }

      },
      //会员提交
      submitMember: function () {
        if (this.memberSelect.length == 0) {
          this.$message({message: "请选择要操作的数据, ", type: "info"});
        } else {
          this.memberForm = {
            username: this.memberSelect[0].username,
            nickname: this.memberSelect[0].nickname,
            mobile: this.memberSelect[0].mobile,
            email: this.memberSelect[0].email,
            memberId: this.memberSelect[0].id
          }
          this.memberDialogVisible = false
        }

      },

      handleSelectionChange: function (param) {
        if (param.length == 1) {
          this.memberSelect = param
        } else {
          param.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item);
          })
        }
      },
      //会员数据初始化
      findMemberPage: function (params) {
        let this_ = this;
        if (params == undefined || params == null) {
          params = {
            pageNum: this_.pageRequest.pageNum,
            pageSize: this_.pageRequest.pageSize
          };
        }
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        this_.filters.start = params.pageNum;
        this_.filters.limit = params.pageSize;
        this.utils.request.queryMemberList(this_.filters, function (res) {
          if (res.data.rows == null) {
            res.data.rows = [];
          }
          this_.tableMemberData = res.data.rows;
          this_.totalSize = Number(res.data.total);
        });
      },
      //会员弹框
      selectMember: function () {
        this.memberDialogVisible = true
        this.findMemberPage()
      },
      //省市县联动
      changeProvince: function (param) {
        this.receiptForm.receiverProvinceId = param.province.code
        this.receiptForm.receiverProvinceName = param.province.value
        this.receiptForm.receiverCityId = param.city.code
        this.receiptForm.receiverCityName = param.city.value
        this.receiptForm.receiverCountryId = param.area.code
        this.receiptForm.receiverRegionName = param.area.value
        this.receiptForm.receiverArea=param.province.value+param.city.value+param.area.value
      },
      //选中店铺
      changeStore: function (data) {
        this.storeId = data.id
        this.storeName = data.storeName
        this.storeLogoUrl = data.storeLogo
      },

      //根据商家和渠道获取店铺列表
      changChannel: function (data) {
        let that = this;
        let param = {}
        param.merchantId = this.merchantId
        param.storeChannels = data
        that.storeOptions=[]
        that.baseForm.storeId=""
        this.utils.request.queryStoreListByChancel(param, function (res) {
          that.storeOptions = res.data;
        });
      },

      //根据商家获取渠道列表
      changMerchant: function (data) {
        let that = this;
        let param = {}
        that.merchantId = data.id
        that.merchantName = data.name
        param.merchantId = data.id
        that.channelOptions = []
        that.baseForm.channelId=""
        that.baseForm.storeId=""
        this.utils.request.queryMerchantChannelListOther(param, function (res) {
          that.channelOptions = res.data;
        });
      },

      //获取商家列表
      queryMerchantListOther: function (data) {
        let that = this;
        this.utils.request.queryMerchantListOther({}, function (res) {
          that.merchantOptions = res.data;
        });
      },

      // 每页数据刷新
      refreshPageRequest: function (pageNum) {
        this.pageRequest.pageNum = pageNum;
        this.findMemberPage(this.pageRequest);
      },
      // 每页条数刷新
      handleSizeChange: function (pageSize) {
        this.pageRequest.pageSize = pageSize;
        this.findMemberPage(this.pageRequest);
      },

      resetMemberFiltersForm(formName) {
        this.memberFilters = {
          username: "",
          nickname: "",
          mobile: "",
        }
        this.findMemberPage()
      },
      resetProductFiltersForm(formName) {
	      this.productFilters = {
		      chineseName: '',
		      productCategoryId: null,
		      brandId: '',
		      code: '',
		      flag: 2
	      }
	      this.findProductPage()
      },
		},

		mounted() {
			//初始化商家下拉框
			this.queryMerchantListOther()
			this.queryProductBrand()
			this.queryBehindCategory()
		}
	};
</script>

<style lang="scss" scoped>

  .el-card__header {
    background: #edf1f2 !important;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 48px;
  }

  .el-row {
    position: initial
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  /deep/ .box-card {
    margin-bottom: 20px;
    text-align: left;
    width: 200px;
    height: auto;
  }
</style>
